<template>
  <div class="certificate-container">
    <!-- 搜索表单 -->
    <div class="custom-form">
      <van-search
        v-model="searchForm.name"
        placeholder="请输入课程名称"
        show-action
        @clear="resetSearch"
        @search="handleSearch"
      >
        <template #action>
          <div @click="handleSearch">搜索</div>
        </template>
      </van-search>

      <van-cell title="考试时间" is-link @click="showCalendar = true" />
      <van-calendar
        v-model:show="showCalendar"
        type="range"
        @confirm="onCalendarConfirm"
      />
    </div>

    <!-- 证书列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-empty
          v-if="certificateList.length === 0"
          description="暂无证书记录"
        />

        <van-card
          v-for="item in certificateList"
          :key="item.id"
          class="certificate-card"
        >
          <template #title>
            <div class="certificate-header">
              <h3>{{ item.subjectName }} 考试证书</h3>
              <van-tag type="success">已通过</van-tag>
            </div>
          </template>

          <template #desc>
            <div class="certificate-info">
              <p><strong>考生姓名：</strong>{{ item.name }}</p>
              <p><strong>考试科目：</strong>{{ item.subjectName }}</p>
              <p><strong>考试分数：</strong>{{ item.score }}分</p>
              <p><strong>考试用时：</strong>{{ formatTime(item.usedTime) }}</p>
              <p v-if="item.testNum > 0">
                <strong>考试题数：</strong>{{ item.testNum }}题
              </p>
              <p>
                <strong>考试时间：</strong>{{ formatDateTime(item.endTime) }}
              </p>
            </div>
          </template>
        </van-card>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { showToast } from "vant";
import subjectTestApi from "@/api/subject/test";

// 响应式数据
const certificateList = ref([]);
const pageSize = ref(2);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const currentPage = ref(1);

const searchForm = reactive({
  name: "",
  timeRange: [],
});

// 新增日历控制变量
const showCalendar = ref(false);

// 计算属性：获取开始和结束时间
const startTime = computed(() => {
  return searchForm.timeRange && searchForm.timeRange.length > 0
    ? searchForm.timeRange[0]
    : new Date("2000-01-01").getTime();
});

const endTime = computed(() => {
  return searchForm.timeRange && searchForm.timeRange.length > 1
    ? searchForm.timeRange[1]
    : new Date("2099-12-31").getTime();
});

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return "";
  return dateTimeString.replace("T", " ");
};

// 格式化考试用时
const formatTime = (timeString) => {
  if (!timeString) return "";
  // 假设timeString格式为 "HH:mm:ss"
  return timeString;
};

// 获取证书列表
const fetchCertificates = async (isRefresh = false) => {
  try {
    loading.value = true; // 开始加载时设置为 true

    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      startTime: startTime.value,
      endTime: endTime.value,
      name: searchForm.name || "",
    };

    const [listRes] = await Promise.all([subjectTestApi.getPassedList(params)]);

    const newList = listRes.data || [];

    if (isRefresh) {
      certificateList.value = newList;
    } else {
      certificateList.value = [...certificateList.value, ...newList];
    }

    loading.value = false;
    if (newList.length < pageSize.value) {
      finished.value = true;
    }

    if (isRefresh) {
      refreshing.value = false;
    }
  } catch (error) {
    console.error("获取证书列表失败:", error);
    showToast({
      message: "获取证书列表失败",
      type: "fail",
    });
    loading.value = false;
    if (isRefresh) {
      refreshing.value = false;
    }
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  finished.value = false;
  certificateList.value = [];
  fetchCertificates(true);
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = "";
  searchForm.timeRange = [];
  currentPage.value = 1;
  finished.value = false;
  certificateList.value = [];
  fetchCertificates(true);
};

// 下拉刷新
const onRefresh = () => {
  currentPage.value = 1;
  finished.value = false;
  fetchCertificates(true);
};

// 上拉加载
const onLoad = () => {
  currentPage.value += 1;
  fetchCertificates();
};

// 日历确认事件处理
const onCalendarConfirm = (dates) => {
  searchForm.timeRange = dates.map((date) => date.getTime());
  showCalendar.value = false;
  handleSearch();
};

// 生命周期钩子
onMounted(() => {
  fetchCertificates(true);
});
</script>

<style scoped>
.certificate-container {
  padding: 16px;
  background-color: #f7f8fa;
}

.custom-form {
  margin-bottom: 16px;
}

.certificate-card {
  margin-bottom: 12px;
  background-color: #fff;
}

.certificate-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.certificate-header h3 {
  margin: 0;
  font-size: 16px;
  color: #323233;
}

.certificate-info p {
  margin: 4px 0;
  font-size: 14px;
  color: #646566;
}

.pagination-container {
  padding: 16px 0;
  display: flex;
  justify-content: center;
}
</style>
